import { defineStore } from 'pinia'
import { LoginService, RegisterService } from '@/api/Auth/auth'
import type { IUser_Login, IUser_Register } from '@/api/Auth/type'
import type { LoginResponse } from '@/libcommon/modules/login'
import type { IUser } from '@/libcommon/modules/user'
import { GetUserInfoService } from '@/api/User/user'

import { useChatStore } from './chat'

export const useUserStore = defineStore(
  'chat-user',
  () => {
    const router = useRouter()

    const chatStore = useChatStore()
    const user = ref<IUser | null>(null)
    const token = ref<string>('')

    const login = async (data: IUser_Login) => {
      const res: LoginResponse = await LoginService(data)
      token.value = res.data.token
      await getUserInfo()
    }

    const register = async (data: IUser_Register) => {
      await RegisterService(data)
    }

    const getUserInfo = async () => {
      const res = await GetUserInfoService()
      // console.log(res);
      user.value = res.data
    }

    const logout = () => {
      token.value = ''
      user.value = null
      setTimeout(() => {
        chatStore.clear()
      }, 0);
      router.push('/login')

    }

    return {
      user,
      token,
      login,
      register,
      logout,
      getUserInfo,
    }
  },
  {
    persist: true,
  },
)
